package org.zhuxian.cn.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.time.YearMonth;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class JwtUtils {
    private static String secretKey;
    private static long expirationTime;
    private static long tokenVersion = YearMonth.now().getMonthValue(); // 修改token版本为当前月份

    @Value("${jwt.secret}")
    public void setSecretKey(String secret) {
        secretKey = secret;
    }

    @Value("${jwt.expiration}")
    public void setExpirationTime(long expiration) {
        expirationTime = expiration * 1000; // 转换秒为毫秒
    }

    // 强制所有用户重新登录
    public static void invalidateAllTokens() {
        tokenVersion = System.currentTimeMillis();
    }
    
    public static String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + expirationTime))
                .claim("version", tokenVersion) // 在token中加入版本号
                .signWith(SignatureAlgorithm.HS512, secretKey)
                .compact();
    }

    public static Claims validateToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(token)
                .getBody();
        
        // 验证token版本号
        Long tokenVer = claims.get("version", Long.class);
        if (tokenVer == null || tokenVer < tokenVersion) {
            throw new RuntimeException("Token已失效，请重新登录");
        }
        return claims;
    }
}